<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/13
 * Time: 17:04
 * Created by Created by Panxsoft.
 */

namespace App\Models;

use App\Models\Concerns\ModelMemorable;
use App\Models\Concerns\ScopeFilterable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Store
 * @property int store_id
 *
 * @property-write array config - 店铺配置
 *
 * @package App\Models
 * @mixin Builder
 */
class Store extends Model
{
    use ModelMemorable;
    use ScopeFilterable;

    /**
     * 店铺无法再后台/数据库中设置默认，通过域名匹配吗
     */
    const STORE_ID_DEFAULT = 0;

    protected $guarded = [];

    protected $table = 'store';

    protected $primaryKey = 'store_id';

    /**
     * @return array
     */
    public static function defaultAttributes(): array
    {
        require_once(base_path('../dw-oc/admin/config.php'));

        return [
            'store_id' => self::STORE_ID_DEFAULT,
            'name' => 'TODO FROM OC CONFIG FILE',
            'url'  => HTTP_SERVER,
            'ssl'  => HTTPS_SERVER,
        ];
    }

    /**
     * @return Store
     */
    public static function default(): self
    {
        return new self(self::defaultAttributes());
    }

    /**
     * @return Store|null
     */
    public static function findByHost(): ?self
    {
        $req = request();

        $req_host = $req->header('X-Forwarded-Host') ?: $req->getHost();

        return self::columnsKeywordOrLike(['url', 'dev_url'], $req_host)->first();
    }
}